#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 31/3/2024 下午9:39
# Author: name
# File: fiel_tools.py
# ide: PyCharm
# description: 操作文件读写的工具类
import json
import ruamel.yaml
import yaml

__all__ = [
    "read_json_file",
    "write_json_file",
    "write_to_file",
    "clean_file",
    "read_file",
    "append_json_file",
    "write_to_yml",
    "read_yml",
    "append_write_to_yml"
]


def read_json_file(file_path):
    try:
        with open(file_path, 'r', encoding="utf-8") as f:
            data = json.load(f)
    except:
        data = {}
    return data


def write_json_file(file_path, data):
    with open(file_path, 'w', encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False)


def write_to_file(file_path, data, model=None):
    if model == "b":
        with open(file_path, 'wb') as f:
            f.write(data)
    elif model == "a":
        with open(file_path, 'a', encoding="utf-8") as f:
            f.write(data)
    else:
        with open(file_path, 'w', encoding="utf-8") as f:
            f.write(data)


def clean_file(file_path):
    with open(file_path, "w") as f:
        f.truncate(0)


def read_file(file_path, model=None):
    if model:
        with open(file_path, 'rb') as f:
            data = f.read()
    else:
        with open(file_path, 'r', encoding="utf-8") as f:
            data = f.read()
    return data


def append_json_file(file_path, data):
    with open(file_path, 'a') as f:
        json.dump(data, f, ensure_ascii=False)
        f.write('\n')


def write_to_yml(file_path, data):
    # 顺序写入新的yml文件中,保证格式不混乱
    with open(file_path, "w", encoding="utf-8") as f:
        ruamel.yaml.round_trip_dump(data, f, default_flow_style=False, allow_unicode=True)


def read_yml(file_path):
    with open(file_path, "r", encoding="utf-8") as f:
        data = ruamel.yaml.YAML(typ='unsafe', pure=True).load(f)
    return data


def append_write_to_yml(file_path, data):
    # 顺序写入新的yml文件中,保证格式不混乱
    with open(file_path, "a", encoding="utf-8") as f:
        yaml.dump(data=data, stream=f, allow_unicode=True)
